<?php
require_once 'InfoManager21.php';

$infoManager = new InfoManager();
$errorMessage = '';
$successMessage = '';

// 验证ID参数
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = '无效的记录ID';
    header('Location: show_info21.php');
    exit;
}

$id = intval($_GET['id']);
$info = $infoManager->getInfoById($id);

// 检查记录是否存在
if (!$info) {
    $_SESSION['error_message'] = '未找到该记录';
    header('Location: show_info21.php');
    exit;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取并过滤输入
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $hobby = trim($_POST['hobby']);

    // 表单验证
    $errors = [];
    if (empty($name)) $errors['name'] = '姓名不能为空';
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "请输入有效的邮箱地址";
    }
    if (empty($phone)) $errors[] = "电话不能为空";

    if (empty($errors)) {
        if ($infoManager->updateInfo($id, $name, $email, $phone, $address, $hobby)) {
            $_SESSION['success_message'] = '记录更新成功';
            header('Location: show_info21.php');
            exit;
        } else {
            $errorMessage = 'Error: 记录更新失败, 请稍后重试';
            // 记录详细错误日志
            error_log("Update failed for ID $id: " . $infoManager->getLastError());
        }
    } else {
        $errorMessage = implode('<br>', $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改信息</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="form-container">
        <h2>修改信息</h2>

        <?php if ($errorMessage) : ?>
            <div class="error-message"><?php echo $errorMessage; ?></div>
        <?php endif; ?>

        <form action="" method="post">
            <input type="hidden" name="id" value="<?php echo $info['id']; ?>">

            姓名: <input type="text" name="name" value="<?php echo $info['name']; ?>" required><br>
            邮箱: <input type="email" name="email" value="<?php echo $info['email']; ?>" required><br>
            电话: <input type="text" name="phone" value="<?php echo $info['phone']; ?>" required><br>
            地址: <input type="text" name="address" value="<?php echo $info['address']; ?>" required><br>
            爱好: <input type="text" name="hobby" value="<?php echo $info['hobby']; ?>" required><br>

            <input type="submit" value="提交更改">
        </form>

        <a href="javascript:history.back();">返回</a>
    </div>
</body>
</html>